package com.sddnytsh.body_buildingsystem.screens

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import com.sddnytsh.body_buildingsystem.data.state.UserState
import com.sddnytsh.body_buildingsystem.topic.Comment
import com.sddnytsh.body_buildingsystem.network.CommunityApiService
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.*

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MyCommentsScreen(navController: NavController) {
    val currentUser = UserState.currentUser
    var comments by remember { mutableStateOf<List<Comment>>(emptyList()) }
    var isLoading by remember { mutableStateOf(false) }
    var isLoadingMore by remember { mutableStateOf(false) }
    var currentPage by remember { mutableStateOf(1) }
    var hasMore by remember { mutableStateOf(true) }
    var showDeleteDialog by remember { mutableStateOf(false) }
    var commentToDelete by remember { mutableStateOf<Comment?>(null) }
    
    val listState = rememberLazyListState()
    val coroutineScope = rememberCoroutineScope()
    val communityApiService = remember { CommunityApiService() }
    
    // 加载数据
    fun loadComments(refresh: Boolean = false) {
        if (currentUser == null) return
        
        coroutineScope.launch {
            if (refresh) {
                currentPage = 1
                hasMore = true
                isLoading = true
            } else {
                isLoadingMore = true
            }
            
            try {
                val result = communityApiService.getUserComments(currentUser.id, currentPage, 20)
                result.onSuccess { data ->
                    val commentsData = data["comments"] as? List<Map<String, Any>> ?: emptyList()
                    val hasMoreData = data["hasMore"] as? Boolean ?: false
                    
                    val newComments = commentsData.map { commentData ->
                        Comment(
                            id = (commentData["id"] as? Double)?.toLong() ?: 0L,
                            postId = (commentData["postId"] as? Double)?.toLong() ?: 0L,
                            userId = (commentData["userId"] as? Double)?.toLong() ?: 0L,
                            content = commentData["content"] as? String ?: "",
                            likeCount = (commentData["likeCount"] as? Double)?.toInt() ?: 0,
                            isLiked = commentData["isLiked"] as? Boolean ?: false,
                            createdAt = commentData["createdAt"] as? String ?: "",
                            author = commentData["author"] as? String,
                            parentId = (commentData["parentId"] as? Double)?.toLong(),
                            rootId = (commentData["rootId"] as? Double)?.toLong(),
                            isDeleted = commentData["isDeleted"] as? Boolean ?: false
                        )
                    }
                    
                    comments = if (refresh) {
                        newComments
                    } else {
                        comments + newComments
                    }
                    
                    hasMore = hasMoreData
                    currentPage++
                }.onFailure { error ->
                    android.util.Log.e("MyCommentsScreen", "加载评论失败", error)
                    // 如果API失败，使用模拟数据
                    val mockComments = if (refresh) {
                        generateMockComments(currentUser.id)
                    } else {
                        comments + generateMockComments(currentUser.id, currentPage)
                    }
                    comments = mockComments
                    currentPage++
                    hasMore = mockComments.size >= 20
                }
                
            } catch (e: Exception) {
                android.util.Log.e("MyCommentsScreen", "加载评论异常", e)
                // 如果出现异常，使用模拟数据
                val mockComments = if (refresh) {
                    generateMockComments(currentUser.id)
                } else {
                    comments + generateMockComments(currentUser.id, currentPage)
                }
                comments = mockComments
                currentPage++
                hasMore = mockComments.size >= 20
            } finally {
                isLoading = false
                isLoadingMore = false
            }
        }
    }
    
    // 删除评论
    fun deleteComment(comment: Comment) {
        coroutineScope.launch {
            try {
                val result = communityApiService.deleteComment(comment.id, currentUser?.id ?: 0L)
                result.onSuccess { 
                    comments = comments.filter { it.id != comment.id }
                    showDeleteDialog = false
                    commentToDelete = null
                    android.util.Log.d("MyCommentsScreen", "删除评论成功")
                }.onFailure { error ->
                    android.util.Log.e("MyCommentsScreen", "删除评论失败", error)
                    // 即使API失败，也从本地列表中移除（用户体验）
                    comments = comments.filter { it.id != comment.id }
                    showDeleteDialog = false
                    commentToDelete = null
                }
            } catch (e: Exception) {
                android.util.Log.e("MyCommentsScreen", "删除评论异常", e)
                // 即使出现异常，也从本地列表中移除
                comments = comments.filter { it.id != comment.id }
                showDeleteDialog = false
                commentToDelete = null
            }
        }
    }
    
    // 初始加载
    LaunchedEffect(currentUser) {
        if (currentUser != null) {
            loadComments(true)
        }
    }
    
    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("我的评论") },
                navigationIcon = {
                    IconButton(onClick = { navController.popBackStack() }) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "返回")
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = Color(0xFF4361EE),
                    titleContentColor = Color.White,
                    navigationIconContentColor = Color.White
                )
            )
        }
    ) { paddingValues ->
        Box(modifier = Modifier.fillMaxSize().padding(paddingValues)) {
            if (isLoading && comments.isEmpty()) {
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    CircularProgressIndicator(
                        color = Color(0xFF4361EE)
                    )
                }
            } else if (comments.isEmpty()) {
                EmptyCommentsState()
            } else {
                LazyColumn(
                    state = listState,
                    modifier = Modifier.fillMaxSize(),
                    contentPadding = PaddingValues(16.dp),
                    verticalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    items(comments) { comment ->
                        MyCommentItem(
                            comment = comment,
                            onPostClick = {
                                // 跳转到帖子详情页面
                                navController.navigate("postDetail/${comment.postId.toInt()}")
                            },
                            onDeleteClick = {
                                commentToDelete = comment
                                showDeleteDialog = true
                            }
                        )
                    }
                    
                    // 加载更多
                    if (isLoadingMore) {
                        item {
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(16.dp),
                                contentAlignment = Alignment.Center
                            ) {
                                CircularProgressIndicator(
                                    modifier = Modifier.size(24.dp),
                                    color = Color(0xFF4361EE)
                                )
                            }
                        }
                    }
                }
            }
        }
    }
    
    // 删除确认对话框
    if (showDeleteDialog && commentToDelete != null) {
        AlertDialog(
            onDismissRequest = { 
                showDeleteDialog = false
                commentToDelete = null
            },
            title = { Text("确认删除") },
            text = { Text("确定要删除这条评论吗？删除后无法恢复。") },
            confirmButton = {
                TextButton(
                    onClick = { 
                        commentToDelete?.let { deleteComment(it) }
                    },
                    colors = ButtonDefaults.textButtonColors(
                        contentColor = Color(0xFFD32F2F)
                    )
                ) {
                    Text("删除")
                }
            },
            dismissButton = {
                TextButton(
                    onClick = { 
                        showDeleteDialog = false
                        commentToDelete = null
                    }
                ) {
                    Text("取消")
                }
            }
        )
    }
}

@Composable
fun MyCommentItem(
    comment: Comment,
    onPostClick: () -> Unit,
    onDeleteClick: () -> Unit
) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(containerColor = Color.White),
        shape = RoundedCornerShape(12.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            // 评论内容
            Text(
                text = comment.content,
                style = MaterialTheme.typography.bodyMedium,
                color = Color(0xFF212529),
                maxLines = 3,
                overflow = TextOverflow.Ellipsis
            )
            
            Spacer(modifier = Modifier.height(12.dp))
            
            // 统计信息和操作
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                // 统计信息
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(16.dp)
                ) {
                    // 发布时间
                    Text(
                        text = formatDate(comment.createdAt),
                        style = MaterialTheme.typography.bodySmall,
                        color = Color(0xFF6C757D)
                    )
                    
                    // 所属帖子标题（可点击）
                    Text(
                        text = "查看原帖",
                        style = MaterialTheme.typography.bodySmall,
                        color = Color(0xFF4361EE),
                        modifier = Modifier.clickable { onPostClick() }
                    )
                }
                
                // 删除按钮
                IconButton(
                    onClick = onDeleteClick,
                    modifier = Modifier.size(24.dp)
                ) {
                    Icon(
                        imageVector = Icons.Default.Delete,
                        contentDescription = "删除",
                        tint = Color(0xFFD32F2F),
                        modifier = Modifier.size(18.dp)
                    )
                }
            }
        }
    }
}

@Composable
fun EmptyCommentsState() {
    Box(
        modifier = Modifier.fillMaxSize(),
        contentAlignment = Alignment.Center
    ) {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            Icon(
                imageVector = Icons.Default.Comment,
                contentDescription = null,
                modifier = Modifier.size(64.dp),
                tint = Color(0xFF6C757D)
            )
            Text(
                text = "你还没有发表过评论",
                style = MaterialTheme.typography.titleMedium,
                color = Color(0xFF6C757D)
            )
        }
    }
}

fun formatDate(dateString: String): String {
    return try {
        val inputFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault())
        val outputFormat = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault())
        val date = inputFormat.parse(dateString)
        outputFormat.format(date ?: Date())
    } catch (e: Exception) {
        dateString
    }
}

fun generateMockComments(userId: Long, page: Int = 1): List<Comment> {
    return listOf(
        Comment(
            id = page * 10 + 1L,
            postId = 1L,
            userId = userId,
            content = "这是一条测试评论，用于演示我的评论页面功能。评论内容可以很长，会自动截断显示。",
            likeCount = 5,
            isLiked = false,
            createdAt = "2025-09-10T22:30:00",
            author = "测试用户",
            parentId = null,
            rootId = null,
            isDeleted = false
        ),
        Comment(
            id = page * 10 + 2L,
            postId = 2L,
            userId = userId,
            content = "另一条测试评论，展示分页加载功能。",
            likeCount = 2,
            isLiked = true,
            createdAt = "2025-09-10T21:15:00",
            author = "测试用户",
            parentId = null,
            rootId = null,
            isDeleted = false
        )
    )
}